<template>
<div class="layout-app" ref='myBox'>
	<!-- main -->
	<el-dialog :title="nameTitle" 
	:visible.sync="addDialogVisible" 
	width="58%" 
	v-dialogDrag 
	:modal="false"
	:before-close="handleClose">
		<!-- 新增 -->
	<div class="addAcc">
			<!-- tabs -->
			<div class="tabs">
				<div class="tabsMain">
					<!-- 表单 header -->
					<div class="headerForm">
						<el-form ref="addForm" :rules="addPlanRules" :model="addForm" label-width="99px" size="mini">
						<el-row :gutter="8">
							  <el-col :xs="val.xs" :sm="val.xs" :md="val.md" :lg="val.lg" :xl="val.xl" type="flex" v-for="(val,i) in formType" :key="i">
								  <!-- input -->
								  <el-form-item v-if="val.type == 'input'" :label="val.label" :prop="val.modelValue">
									<el-input v-model="$data.addForm[val.modelValue]" :placeholder="val.placeholder" :disabled="val.disabled" ></el-input>
								  </el-form-item>
								  <!-- select -->
								  <el-form-item v-if="val.type == 'select'" :label="val.label" :prop="val.modelValue">
									<el-select v-model="$data.addForm[val.modelValue]" filterable placeholder="请选择"
									@change="handleChange" :disabled="val.disabled">
										<el-option v-for="item in $data[val.op]" :key="item.id" :label="item.label" :value="item.id"> 
											<span style="color: #8492a6; font-size: 12px">{{ item.label }}</span>
										</el-option>
									</el-select>
								  </el-form-item>
								  <!-- date -->
								  <el-form-item v-if="val.type == 'date'" :label="val.label" :prop="val.modelValue">
									<el-date-picker class="autoWidth" :picker-options="pickerOptions" :disabled="val.disabled"
									type="date" value-format="yyyy-MM-dd" placeholder="选择日期" v-model="$data.addForm[val.modelValue]"></el-date-picker>
								  </el-form-item>
								  <!-- btn -->
								  <el-form-item v-if="val.type == 'btn'">
									<el-button type="primary" plain @click="clickEvents(val,i)">{{ val.label }}</el-button>
								  </el-form-item>
								  <!-- textarea -->
								  <el-form-item v-if="val.type == 'textarea'" :label="val.label" :prop="val.modelValue">
								  	<el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="$data.addForm[val.modelValue]"></el-input>
								  </el-form-item>
							  </el-col>
							</el-row>
						</el-form>
					</div>
					<!-- 表单 Main -->
					<div class="mainForm">
						<el-form ref="addMainForm" :rules="addPlanRules" :model="addMainForm" label-width="80px" size="mini"
						label-position="right">
						<el-row :gutter="8">
							  <el-col :xs="val.xs" :sm="val.xs" :md="val.md" :lg="val.lg" :xl="val.xl" type="flex" v-for="(val,i) in formMainType" :key="i">
								  <!-- input -->
								  <el-form-item v-if="val.type == 'input'" :label="val.label" :prop="val.modelValue">
									<el-input :suffix-icon='val.prefix' v-model="$data.addMainForm[val.modelValue]" :placeholder="val.placeholder" :disabled="val.disabled" ></el-input>
								  </el-form-item>
								  <!-- input 数量 -->
								  <el-form-item v-if="val.type == 'inputNum'" :label="val.label" :prop="val.modelValue">
								  	<el-input placeholder="" v-model="$data.addMainForm[val.modelValue]" class="input-with-select">
								  	    <el-select v-model="purcType" slot="prepend" @change="SelectedPurcType" placeholder="库存类型">
								  	      <el-option label="最小单位" value="1"></el-option>
								  	      <el-option label="包装单位" value="2"></el-option>
								  	    </el-select>
								  	    <span slot="append" icon="el-icon-search">{{ purcType == 1 ? minUnt : unt }}</span>
								  	  </el-input>
								  	<!-- <el-input :suffix-icon='val.prefix' v-model="$data.addMainForm[val.modelValue]" @blur="handleInput(val,i)" :disabled="val.disabled" ></el-input> -->
								  </el-form-item>
								  <!-- select -->
								  <el-form-item v-if="val.type == 'select'" :label="val.label" :prop="val.modelValue">
									<el-select v-model="$data.addMainForm[val.modelValue]" filterable placeholder="请选择" @focus="sname(val,i)"
									@change="handleChange" :disabled="val.disabled">
									<el-group>
									  <!-- 固定头部 -->
									  <div class="select-header" slot="header" 
									  style="font-size: 12px;font-weight: bold;display: flex;justify-content: space-around;padding: 12px;background-color: #f1f1f1;">
									    <span>名称</span>
									    <span>编码</span>
									  </div>
										<el-option v-for="item in $data[val.op]" :key="item.id" :label="item.label" :value="item.id"> 
											<div class="chose" style="border: 1px solid #000;display: flex;justify-content: space-around;">
												<span style="float: left;font-size: 12px;width:128px;border: 1px solid #000;padding-left:8px;">{{ item.label }}</span>
												<span style="float: right;font-size: 12px;width:88px;border: 1px solid #000;padding-left:8px;">{{ item.code }}</span>
											</div>
										</el-option>
									</el-group>
									</el-select>
								  </el-form-item>
								  <!-- date -->
								  <el-form-item v-if="val.type == 'date'" :label="val.label" :prop="val.modelValue">
									<el-date-picker class="autoWidth" :picker-options="pickerOptions" @focus="testDate(val,i)" @change="changDate"
									type="date" value-format="yyyy-MM-dd" placeholder="选择日期" v-model="$data.addMainForm[val.modelValue]"></el-date-picker>
								  </el-form-item>
								  <!-- btn -->
								  <el-form-item v-if="val.type == 'btn'">
									<el-button type="primary" plain @click="clickEvents(val,i)">{{ val.label }}</el-button>
								  </el-form-item>
								  <!-- tag -->
								  <el-form-item v-if="val.type == 'tag'" style="margin-left: -68px;">
								  	<el-tag size="small">{{ pacUnt }}</el-tag>
								  </el-form-item>
							  </el-col>
							</el-row>
						</el-form>
					</div>
					<!-- table -->
					<div class="table">
						<el-table :data="tableData" border @row-dblclick="handledbRow">
							<!-- 在el-table-column中添加可编辑列 -->
							<el-table-column prop="purcCnt" label="采购数量" width="88">
							  <template slot-scope="scope">
							    <el-input size="mini"
								  v-if="scope.row.editing"
								  v-model.number="scope.row.purcCnt"
								  @input="handleInputChange(scope.row)"
								  placeholder="请输入"/>
							    <span v-else>{{ scope.row.purcCnt }}</span>
							  </template>
							</el-table-column>
							<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
							<!-- fixed -->
							<el-table-column fixed="left" label="行号" type="index" width="68" align="center"></el-table-column>
							<!-- edit -->
							<el-table-column fixed="right" label="操作" width="148">
								<template slot-scope="scope">
									<div class="editbox" style="text-align: center;">
										<template v-if="!scope.row.editing">
											<el-button type="primary" @click="enableEditing(scope.row)" size="mini">编辑</el-button>
											<el-button type="danger" @click.native.prevent="deleteRow(scope.$index, tableData)" size="mini">删除</el-button>
										</template>
										<template v-else>
											<el-button type="success" @click="saveEdit(scope.row)" size="mini">完成</el-button>
											<el-button type="info" @click="cancelEdit(scope.row)" size="mini">取消</el-button>
										</template>
									</div>
								</template>
							</el-table-column>
						</el-table>
						<div class="total">
							<span>合计金额：</span><el-input v-model="cbValue" style="width: 128px;" size="mini" :disabled='totaldisabled'></el-input>
<!-- 							<span style="margin-left: 12px;">零售合计：</span><el-input v-model="lsValue" style="width: 128px;" size="mini" :disabled='totaldisabled'></el-input> -->
						</div>
					</div>
				</div>
				
			</div>
		  <div slot="footer" class="dialog-footer" v-if="!isEditShow">
			<el-button :loading="loading" size="mini" type="primary" @click="addSubmit">提交</el-button>
			<el-button :loading="loading" size="mini" type="info" @click="draftSubmit">存为草稿</el-button>
			<el-button :loading="loading" size="mini" @click="addDialogVisible = false">关闭</el-button>
		  </div>
		  <!-- 编辑提交 -->
		  <div slot="footer" class="dialog-footer" v-if="isEditShow">
		  	<el-button :loading="loading" size="mini" type="info" plain @click="draftEditSubmit">修改保存草稿</el-button>
		  	<el-button :loading="loading" size="mini" type="primary" plain @click="editSubmit">修改提交</el-button>
		  	<el-button :loading="loading" size="mini" plain @click="addDialogVisible = false">关闭</el-button>
		  </div>
	</div>
</el-dialog>
</div>

</template>

<script>
// self
import AccType from './AddPlanType.js'
import AccMainType from './AddPlanMainType.js'
import addForm from './addForm.js' //Form表单
// prop

// ext
import { getLunar } from 'chinese-lunar-calendar'

// 接口
// import { addTcm,TcmDetail,editTcm,traMediciList,selectDropDownList,selectInformation ,} from "@/api/PSI.js";

import { addTcm,editTcm,TcmDetail,traMediciList,selectDropDownList,selectInformation } from "@/api/systemCatalogue/traMedici.js";
	
export default {
	props: ['parentMethod'],
	inject: ['reload'], // 无痕刷新
	components:{
		
	},
	data(){
		return{
			//str
			tableWidth:'', //右侧表格动态宽度
			nameTitle:'新增采购计划[中药]',
			purcType:'', // 库存类型 = > 判断大小单位 0最小单位,1包装单位
			value:'',
			deptCode:'',
			cbValue:'',
			lsValue:'',
			getLunarDay: '',
			areaCode:'',
			areaPName:'',
			unt:'', // 包装单位 （数量：盒？包？g?）
			minUnt:'', // 最小单位 （数量：盒？包？g?）
			pacUnt:"", // 包装单位
			idx:'',
			year: new Date().getFullYear(),
			month: new Date().getMonth() + 1,
			date: new Date().getDate(),
			lunarDate: '',//农历
			// 1 - 3
			firstName:'',
			seconedName:'',
			thirdName:'',
			//num
			
			//ble
			disabled:true,
			loading:false,
			totaldisabled:true,
			addghdwDialog:false,
			isEditShow:false,
			selectDisabled:true,
			addDialogVisible:false,
			//arr
			formType:[], // 表单头部内容
			formMainType:[], // 表单主体内容
			tableData:[],
			selectOption:[{id:2,label:'中药库'}],// 申请科室
			cgOption:[
				{id:1,label:'集中采购',value:'集中采购'},{id:2,label:'谈判药品',value:'谈判药品'},{id:3,label:'带量采购',value:'带量采购'},
				{id:4,label:'备案采购',value:'备案采购'},{id:5,label:'非平台采购',value:'非平台采购'},{id:6,label:'精麻药品',value:'精麻药品'},
			],
			sexOptions:[{id:1,label:'男',value:'男'},{id:2,label:'女',value:'女'}],
			marryiedOptions:[{id:1,label:'未婚',value:'未婚'},{id:2,label:'已婚',value:'已婚'},{id:3,label:'离异',value:'离异'},{id:4,label:'丧偶',value:'丧偶'},{id:5,label:'再婚',value:'再婚'}],
			statusOptions:[{id:1,label:'是',value:'是'},{id:2,label:'否',value:'否'}],
			bloodOptions:[{id:1,label:'A型血',value:'A型血'},{id:2,label:'B型血',value:'B型血'},{id:3,label:'O型血',value:'O型血'},{id:4,label:'AB型血',value:'AB型血'},{id:5,label:'RH（熊猫）型血',value:'RH（熊猫）型血'}],
			nameOption:[],
			dosformOptions:[{ id:1,label:'饮片'},{ id:2,label:'颗粒'}],
			tableRows:[
				// { name:"系统序号", prop:"id", nz:"nz" },{ name:"药品序号", prop:"id", nz:"nz" },
				{ name:"药品名称", prop:"drugName"},{ name:"规格描述", prop:"drugSpec"},
				{ name:"药品编码", prop:"code"},{ name:"生产厂家", prop:"prodentpName"},
				{ name:"包装单位", prop:"pacUnt"},{ name:"最小单位", prop:"dosUnt"},
				{ name:"参考单价", prop:"purcPric"},{ name:"参考金额", prop:"purcAmt"},
				// { name:"合同数量", prop:"gdTime", type:"" },{ name:"已购数量", prop:"zf", type:"" },{ name:"库存数量", prop:"ph", type:"" },
				// { name:"近期销量", prop:"scrq", type:"" }
			],
			// 表单验证规则
			addPlanRules:{
				putInDep: [{ required: true, message: '此项必填！', trigger: 'change' }],
				applicantId: [{ required: true, message: '此项必填！', trigger: 'change' }],
				supplyCandidateId: [{ required: true, message: '此项必填！', trigger: 'change' }],
				drugName: [{ required: true, message: '此项必填！', trigger: 'change' }],
				purcCnt: [
				    { required: true, message: '入库的数量为必填项！', trigger: 'blur' },
				    { 
				      validator: (rule, value, callback) => {
				        // 验证是否为非0正整数
				        if (!/^[1-9][0-9]*$/.test(value)) {
				          callback(new Error('入库的数量为非0正整数!'));
				        } 
				        // 验证是否选择了库存类型
				        else if (this.addMainForm.purcType == '') {
				          callback(new Error('请先选择库存类型!'));
				        } else {
				          callback();
				        }
				      },
				      trigger: 'blur'
				    }
				],
				// purCnt: [{ required: true, pattern: /^[1-9][0-9]*$/, message: '请输入正确的数量！', trigger: 'blur' }],
			},
			//obj
			pickerOptions: {
			  shortcuts: [
				{ text: '今天', onClick(picker) { picker.$emit('pick', new Date()); }}, 
				{ text: '昨天', onClick(picker) { const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24);picker.$emit('pick', date);}}, 
				{ text: '一周前',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);picker.$emit('pick', date);}},
				]
			},
			//obj
			addForm:{}, // form表单 * 
			addMainForm:{}, // form主体表单 * addForm.list
			options:[],
			ssrOption:[],
			gysOption:[],
			countryOptions:[],
			MZOptions:[],
		}
	},
	mounted() {
		// 获取接口参数
		this.getAddForm();
		this.getGys();
		this.getSqr();
		this.getDrug();
		//获取动态盒子宽度，实时赋值给右侧
		this.$nextTick(() => {
		    const box = this.$refs.myBox;
		    this.tableWidth = box.offsetWidth - 288;
		    console.log('盒子的宽度是:', this.tableWidth);
		});
		this.addForm.busDate = new Intl.DateTimeFormat('zh-CN').format(new Date()).replace(/\//g, '-');
	},
	methods:{
		// 时间处理
		changDate(val){
			let i = this.idx
			switch(i) {
				case 5:
				function formatDate(date) {
				  const year = date.getFullYear();
				  const month = (date.getMonth() + 1).toString().padStart(2, '0');
				  const day = date.getDate().toString().padStart(2, '0');
				  return `${year}-${month}-${day}`;
				}
				
				// 使用示例
				const now = new Date();
				// this.addForm.busDate = formatDate(val);
			}
		},
		// 库存类型选择
		SelectedPurcType(val){
			this.addMainForm.purcType = val;
		},
		deleteRow(index, rows) {
		    rows.splice(index, 1);
		    this.getTotalAmt(); // 删除行后重新计算总金额
		},
		handleSelectCost(val) {
		  this.addForm.nativePlace = val.join(',')
		},
		async getGys(){
			// 供应商下拉列表
			let rs = await selectDropDownList()
			this.gysOption = rs.data.content.map(obj => {
			  // 将 name 替换为 label，并保留其他字段
			  return { label: obj.supplierName , ...obj };
			});
		},
		// 药品下拉选择框 => 中药
		async getDrug(){
			let res = await traMediciList()
			console.log(res.data.content)
			this.nameOption = res.data.content.map(obj => {
			  // 将 name 替换为 label，并保留其他字段
			  return { label: obj.name , ...obj };
			});
		},
		async getSqr(){
			// 申请人下拉列表
			// let rs = await selectList()
			let rrs = await selectInformation();
			this.ssrOption = rrs.data.map(obj => {
			  // 将 name 替换为 label，并保留其他字段
			  return { label: obj.fullName , ...obj };
			});
		},
		// 挂载或销毁前后重新赋值后端参数
		getAddForm(){
			// 左侧提交表单
			this.addForm = addForm.map(v => {return v })[0]; // Form
			this.addMainForm = this.addForm.list[0];
			console.log(this.addMainForm,'原始的接口参1111数数据');
			// 定义数据来源
			this.formType = AccType.map(function(val) { return val })
			this.formMainType = AccMainType.map(function(val) { return val })
			// 解构赋值排除 list 属性 => 弃用
			// this.addHeadrForm = addForm.map(item => { let { list, ...newItem } = item; return newItem })[0];
		},
		// 打开模态框
		async open(param){
			if(param == '新增'){
				this.addDialogVisible = true;
				this.isShow = true
				this.isEditShow = false;
				this.nameTitle = '新增采购计划【中药】'
			}else{
				this.nameTitle = '编辑采购计划【中药】'
				this.addDialogVisible = true;
				this.isEditShow = true;
				let res = await TcmDetail({ id:param.id });
				if(res.code === 200){
					// console.log(res.data);
					// 遍历 res.data 的所有键名
					for (let key in res.data) {
					  // 检查键名是否在对象 A 中存在
					  if (this.addForm.hasOwnProperty(key)) {
						// 如果存在，将 B 中的值更新到 A 中
						this.addForm[key] = res.data[key];
					  }
					}
					// this.addForm.markUpId == 2 ? this.addForm.markUpFixed = 1 : this.addForm.markUpFixed = 0
					this.tableData = this.addForm.list
					this.addForm.id = param.id
				}
			}
		},
		// 修改保存
		async editSubmit(){
			//触发验证表单
			this.$refs.addForm.validate(async(valid) => {
			if(valid){
			this.addForm.state = 2
			this.addForm.list = this.tableData
				if(this.tableData.length === 0){
					this.$message({type: 'error',message: '暂无对应的单据明细...' });
				}else{
					console.log(this.addForm);
					this.loading = true;
					let result = await editTcm(this.addForm)
					if (result.code === 200) {
					this.$message({ type: 'success', message: result.message });
					this.parentMethod(); // 更新数据驱动 => 父组件 shopPlan
					this.loading = false;
					this.addDialogVisible = false;
					this.$refs['addMainForm'].resetFields();
					} else {
					this.$message.error(result.message)
					}
				}
			}
			})
		},
		// 修改草稿保存
		async draftEditSubmit(){
			//触发验证表单
			this.$refs.addForm.validate(async(valid) => {
			if(valid){
			this.addForm.state = 0
			this.addForm.list = this.tableData
			console.log(this.addForm);
			this.loading = true;
			let result = await editTcm(this.addForm)
				if (result.code === 200) {
					this.$message({ type: 'success', message: '采购计划草稿：已修改！！' });
					this.parentMethod(); // 更新数据驱动 => 父组件 shopPlan
					this.loading = false;
					this.addDialogVisible = false;
					this.$refs['addMainForm'].resetFields();
				} else {
					this.$message.error(result.message)
				}
			}
			})
		},
		testDate(val,i){
			this.idx = val.id
		},
		handleInput(v,i){
			this.idx = i;
			// i event
			switch (i) {
				case 5:
					this.getTotalAmt();
				break;
			}
		},
		//  select聚焦
		async sname(val,i) {
			// val.id = i;
			this.idx = i;
			console.log(i);
			// i event
			switch (i) {
				case 0:
					this.getDrug();
				break;
			}
		},
		// SelectVal to editForm
		handleChange(val){
			console.log(val);
			// i event
			switch (this.idx) {
				case 0:
				// 字段映射
				// 根据 NameOptions绑定的id 找到对应的对象
					let vrs = this.nameOption.find(name => name.id === val);
					this.addMainForm.drugId = vrs.id // 药品id
					this.addMainForm.drugName = vrs.name // 药品名称
					this.addMainForm.dosform = vrs.dosform // 剂型
					this.addMainForm.drugSpec = vrs.drugspec // 规格
					this.addMainForm.code = vrs.code // 编码
					this.addMainForm.purcPric = vrs.costPric // 参考单价
					// this.addMainForm.purcAmt = vrs.purcAmt // 参考金额 = 单价 * 数量
					this.addMainForm.prodentpName = vrs.manufacturerName
					this.addMainForm.prodentpNameId = vrs.manufacturerId
					this.addMainForm.pacUnt = vrs.pacUnt // 包装单位
					this.addMainForm.dosUnt = vrs.dosUnt // 最小单位
					this.unt = vrs.pacUnt // 包装单位
				    this.minUnt = vrs.dosUnt // 最小单位
				break;
				case 3:
					let rs = this.gysOption.find(name => name.id === val)
					this.addForm.supplyCandidateName = rs.supplierName // 供货单位
					this.addForm.supplyCandidateId = rs.id // 供货单位序号
				break;
			}
		},
		// 循环按钮点击事件
		clickEvents(val,i){
			this.idx = i;
			switch (i) {
				case 3:
					// 有效状态
					this.addghdwDialog = true;
					break;
				case 10:
					//触发验证表单
					this.$refs.addMainForm.validate(async(valid) => {
					if(valid){
						if(this.tableData.length == 0){
							this.getTotalAmt();
							this.cbValue = this.addForm.totalAmt
							this.tableData.push(JSON.parse(JSON.stringify(this.addMainForm)));
							this.$refs['addMainForm'].resetFields();
						}else{
							// 判断是否新增的药品序号和前一条相同
							let res = this.tableData.some(i => i.drugId === this.addMainForm.drugId && i.id === this.addMainForm.id)
							// 重复数据
							if(res === true){
								this.$message.error('表格中已存在相同药品：' + this.addMainForm.drugName + '，请勿重复添加！')
							}else{
								// 只计算新添加行的金额，并加到总和中
								// this.cbValue += this.addMainForm.purcAmt;
								this.getTotalAmt();
								this.$message.success('已添加！')
								this.tableData.push(JSON.parse(JSON.stringify(this.addMainForm)))
								this.$refs['addMainForm'].resetFields();
							}
						}
						}
					})
				break;
			}
		},
		// 计算总成本合计
		getTotalAmt() {
		    // 先计算当前表单行的金额
		    this.addMainForm.purcAmt = this.addMainForm.purcPric * this.addMainForm.purcCnt
		    let cbTotal = 0;
		    // 如果表格中没有数据，使用表单中的金额
		    if(this.tableData.length === 0) {
		        this.addForm.totalAmt = this.addMainForm.purcAmt;
		        this.cbValue = this.addForm.totalAmt;
		    } else {
		        // 计算表格中所有行的总金额
		        this.tableData.forEach(row => {
		            // 确保每行的金额是计算过的
		            if(!row.purcAmt) {
		                row.purcAmt = row.purcPric * row.purcCnt;
		            }
		            cbTotal += row.purcAmt;
		        });
		        
		        // 加上当前表单行的金额（如果还未添加到表格）
		        if(!this.tableData.some(row => row.drugId === this.addMainForm.drugId)) {
		            cbTotal += this.addMainForm.purcAmt;
		        }
		        
		        this.cbValue = cbTotal;
		        this.addForm.totalAmt = cbTotal;
		    }
		},
		// 添加图片加载失败处理
		handleImgError(e) {
		    e.target.src = require('@/assets/images/addPlanSpoke.png')
		},
		//新增保存
		async addSubmit(){
			//触发验证表单
			this.$refs.addForm.validate(async(valid) => {
			if(valid){
				this.addForm.state = 2
				this.addForm.list = this.tableData
				console.log(this.addForm);
				this.loading = true;
				let result = await addTcm(this.addForm)
				if (result.code === 200) {
					this.$message({ type: 'success', message: '采购计划新增成功！' });
					this.parentMethod(); // 更新数据驱动 => 父组件 shopPlan
					this.loading = false;
					this.addDialogVisible = false;
					this.$refs['addForm'].resetFields();
				}
			}
			})
		},
		// 草稿保存
		async draftSubmit(){
			//触发验证表单
			this.$refs.addForm.validate(async(valid) => {
			if(valid){
				this.addForm.state = 0
				this.addForm.list = this.tableData
				console.log(this.addForm);
				this.loading = true;
				let result = await addTcm(this.addForm)
				if (result.code === 200) {
					this.$message({ type: 'success', message: '采购计划新增成功！' });
					this.parentMethod(); // 更新数据驱动 => 父组件 shopPlan
					this.loading = false;
					this.addDialogVisible = false;
					this.$refs['addForm'].resetFields();
				}
			}
			})
		},

		// 启用编辑状态
		enableEditing(row) {
		  // 确保整个对象是响应式的
		  const reactiveRow = this.$set(this.tableData, this.tableData.indexOf(row), {
			...row,
			editing: true,
			originalData: { ...row } // 保存原始数据
		  });
		  this.oldData = reactiveRow;
		  console.log(this.oldData, 'oladuygasgoi');
		},
		
		// 保存编辑
		saveEdit(row) {
		  this.loading = true;
		  setTimeout(() => {
			// 禁用编辑状态
			this.$set(row, 'editing', false);
			// 重新计算总金额
			row.purcAmt = row.purcPric * row.purcCnt;
			row.saleAmt = row.salePric * row.purcCnt;
			this.getTotalAmt();
			// 更新表格数据
			this.tableData = this.tableData.map(item => item);
			this.$refs['addMainForm']?.resetFields();
			this.loading = false;
		  }, 800); // 减少延迟时间
		},
		
		// 取消编辑
		cancelEdit(row) {
		  // 恢复原始数据
		  Object.assign(row, row.originalData);
		  this.$set(row, 'editing', false);
		  delete row.originalData;
		},
		
		// 处理输入变化
		handleInputChange(row) {
		  // 重新计算总金额
		  this.addForm.costAmt = row.purcAmt = row.purcPric * row.purcCnt;
		  this.addForm.saleAmt = row.saleAmt = row.salePric * row.purcCnt;
		  this.getTotalAmt();
		},
		//sons
		// db events
		handledbRow(row, column, event){
			if(row){ this.addForm = row; this.watchDialogVisible = true } else { console.log('fail'); }
			// console.log(this.addForm);
			this.formdisabled = true
		},
		// col 里面包含了表头字段和名称，list 是表格数据
		columnWidth(col, list) {
		  let prop = col.prop,lab = col.lab;
		  let width = 20; // 设定一个最小值
		  let maxlenStr = ""; // 最长字符串
		  for (let info of list) {
			if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		  }
		  width = Math.max(width, len(lab), len(maxlenStr));
		  // 表格自带的内边距(20px) 自调
		  return width + 12; // 这里加了 12px
		  function len(str) {
			// 实际分配长度可根据需要自行调整
			let length = 12;
			for (const char of str + "") {
			  // 英文小写字符 8px
			  if ("a" <= char && char <= "z") length += 12;
			  // 数字
			  else if (Number.isFinite(Number(char))) length += 8;
			  // 英文大写字符 8px
			  else if ("A" <= char && char <= "Z") length += 8;
			  // 中文字符 28px
			  else if (char >= "\u4e00" && char <= "\u9fa5") length += 12;
			  // 其他 8px
			  else length += 8;
			}
			return length;
		  }
		},
		// 关闭Model
		handleClose(done) {
			this.$confirm('关闭此界面会清空现已选择的内容, 是否继续?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '取消',
			  type: 'warning'
			}).then(() => {
				//清空表单和list
				this.$refs['addForm'].resetFields();
				this.$refs['addMainForm'].resetFields();
				this.tableData = [];
				done(); //关闭
			}).catch(() => {
			  this.$message({ type: 'info', message: '已取消' });          
			});
		},
	},
	
}
</script>

<style lang="less" scoped>
.layout-app{
    width: 100%;
    height: 100%;
    display: flex;
	background-color: f8f8f8;
	/deep/ .el-dialog__body{
		padding: 12px;
	}
	/deep/ .el-dialog__header{
		padding: 4px;
		background-color: #007bb0;
	}
	/deep/ .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
		margin-bottom: 12px;
	}
	/deep/ .el-dialog__title{
		color: #fff;
		font-size: 12px;
	}
	/deep/ .el-dialog__headerbtn{
		top: 10px;
	}
	/deep/ .el-dialog__headerbtn .el-dialog__close{
		color: #fff;
	}
	/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
		background-color: brown;
	}
    .addAcc{
		// 选项卡
		.tabs{
			
			.tabsMain{
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				align-items: center;
				width: 100%;
				.table{
					width: 100%;
					margin-top: 12px;
					/deep/ .el-table .cell{
						font-size: 12px;
						font-weight: 400;
						color: #0c0c0c;
						text-align: left;
					}
					/* 自定义高亮颜色 */
					::v-deep .el-table__body tr.current-row > td {
					  background-color: #00557f !important;
					  color: #f9f9f9; /* 可选：修改文字颜色 */
					}
					/deep/ .el-table .el-table__cell{
						padding: 8px 0;
					}
				}
				.total{
					display: flex;
					height: 48px;
					align-items: center;
					span{
						font-size: 12px;
					}
				}
				// 第一层头部表单
				.headerForm{
					/deep/ .el-select >.el-input{
						width: 100%;
					}
					/deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner{
						width: 100%;
					}
					/deep/ .el-form-item__label{
						display: flex;
						justify-content: right;
						font-size: 12px;
					}
					/deep/ .el-input--mini .el-input__inner{
						height: 26px;
					}
					border: 1px solid #EBEEF5;
					padding: 12px;
					/deep/ .el-form-item__label{
						display: flex;
						justify-content: start;
						font-size: 12px;
						padding: 0;
					}
				}
				// 第二层主体表单
				.mainForm{
					/deep/ .el-select >.el-input{
						width: 100%;
					}
					.input-with-select{
						/deep/ .el-select .el-input {
							width: 108px;
						}
					}
					
					/deep/ .input-with-select .el-input-group__prepend {
						background-color: #fff;
					}
					/deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner{
						width: 100%;
					}
					/deep/ .el-form-item__label{
						display: flex;
						justify-content: center;
						font-size: 10px;
						padding: 0;
					}
					/deep/ .el-input--mini .el-input__inner{
						height: 26px;
					}
					padding: 12px;
					margin-top: 8px;
					border: 1px solid #EBEEF5;
				}
			}	
		}
		.dialog-footer{
			display: flex;
			justify-content: right;
		}
	}
}
</style>